<?php

namespace App\Utils;

class Sign{
    /**
     *签名验证
     */
    public static function colsign($data, $key){
        ksort($data);
        $list = [];
        foreach($data as $k => $v){
            if($k != "signature" && $k != "sign"){
                if(is_array($v)){
                    $v = json_encode($v, true);
                }
                $list[] = "$k=$v";
            }
        }
        $str = implode("&", $list);
        $str .= "&key=$key";
        self::writeLog(__FUNCTION__.'/'.__LINE__.'/_INFO', $str);
        return strtoupper(md5($str));
    }

    /**
     *日志
     */
    public static function writeLog($action, $data){
        $path = './logs/texlog/'.date("Ymd").'/'.date("Ymd"). '_request_log.txt';
        $dir = dirname($path);
        if(!file_exists($dir)){
            //iconv防止中文乱码
            $res = mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
        }
        $fopen = fopen($path, "a");
        fwrite($fopen, var_export(date("Y-m-d H:i:s") . '_' . $action . '_' . json_encode($data, JSON_UNESCAPED_UNICODE), true)."\n\r");
        fclose($fopen);
    }

    /**
     *获取随机串
     */
    public static function getNonceStr(){
        return strtoupper(md5(time() . mt_rand(0, 100000) . substr('abcdefg', mt_rand(0, 7))));
    }

    /**
     *json返回
     */
    public static function getMsg($res){
        return json_encode($res, JSON_UNESCAPED_UNICODE);
    }
}
